package com.google.code.HomeSeek;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import android.util.Log;

public class HomeSeekActivity extends Activity {

	static final String LOG_ID = "HomeSeek.MainActivity";
	static final String PREFS_NAME = "HomeSeekPreferences";

	static final String GO_HOME_PREF = "GoHome";
	static final String IGNORE_DURING_CALLS_PREF = "IgnoreDuringCalls";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Restore preferences
		final SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		boolean goHome = settings.getBoolean(GO_HOME_PREF, true);

		if (goHome) {
			startService();
		} else {
			Log.d(LOG_ID, "Not starting service");
		}

		final CheckBox ghCheckBox = (CheckBox) findViewById(R.id.goHome);
		if (ghCheckBox == null) {
			Log.e(LOG_ID, "Couldn't find checkbox!!!");
		}
		ghCheckBox.setChecked(goHome);

		ghCheckBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// Perform action on click
				Log.d(LOG_ID, "goHome checkbox now " + (isChecked?"checked":"unchecked"));
				SharedPreferences.Editor editor = settings.edit();
				editor.putBoolean(GO_HOME_PREF, isChecked);
				editor.commit();
				if (isChecked) {
					startService();
				} else {
					stopService();
				}
			}
		});

		boolean ignoreDuringCalls = settings.getBoolean(IGNORE_DURING_CALLS_PREF, true);
		final CheckBox icCheckBox = (CheckBox) findViewById(R.id.ignoreCalls);
		icCheckBox.setChecked(ignoreDuringCalls);

		icCheckBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// Perform action on click
				Log.d(LOG_ID, "Ignore during calls checkbox now " + (isChecked?"checked":"unchecked"));
				SharedPreferences.Editor editor = settings.edit();
				editor.putBoolean(IGNORE_DURING_CALLS_PREF, isChecked);
				editor.commit();
			}
		});

		Button aboutButton = (Button) findViewById(R.id.aboutButton);
		aboutButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("org.openintents.action.SHOW_ABOUT_DIALOG");
				startActivityForResult(intent, 0);
			}
		});

		Log.d(LOG_ID, "End onCreate");
	}

	void startService() {
		Log.d(LOG_ID, "Starting service");
		Intent serviceIntent = new Intent(this, InstallerService.class);
		startService(serviceIntent);
	}
	
	void stopService() {
		Log.d(LOG_ID, "Stopping service");
		Intent serviceIntent = new Intent(this, InstallerService.class);
		stopService(serviceIntent);
	}
}
